import 'package:get/get.dart';
import 'package:kkhousekeep/models/image_upload_entity.dart';
import 'package:kkhousekeep/net/me_account_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/page/login/login_controller.dart';
import 'package:kkhousekeep/page/public/take_picture_screen.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/log.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';
import 'package:kkhousekeep/tools/toast_util.dart';

class FacePhotoController extends GetxController {
  var headPortrait = "".obs;
  var faceNetPath = "";
  UserType? userType;
  late MeAccountConnect _meAccountConnect;

  selectImage() {
    Get.to(
      () => TakePictureScreen(
        uerGallery: true,
        photoPathCallBack: <PickPictureModel>(model) {
          headPortrait.value = model.netPath;
          faceNetPath = model.netPath;
        },
      ),
    );
  }

  takePhoto() {
    logD("takePhoto");
    Get.to(
      () => TakePictureScreen(
        photoPathCallBack: <PickPictureModel>(model) {
          headPortrait.value = model.netPath;
          faceNetPath = model.netPath;
        },
      ),
    );
  }

  save() {
    if (faceNetPath.isNotEmpty) {
      summitFacePortrait();
    } else {
      ToastUtils.showToast(tip: "请选择或拍摄照片");
    }
  }

  Future<void> summitFacePortrait() async {
    ImageUploadEntity? response;
    if (userType == UserType.property) {
      response = await _meAccountConnect.modifyAvatarForProperty(
          imageUrl: faceNetPath);
    } else {
      response = await _meAccountConnect.updateUserInfo(userImage: faceNetPath);
    }
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      getSp().setUserHeadPortrait(faceNetPath);
      ToastUtils.showToast(tip: "提交成功");
      Get.back();
      return;
    }
    DialogUtil.showNetworkFail();
  }

  @override
  void onInit() {
    _meAccountConnect = Get.put(MeAccountConnect());
    super.onInit();
    loadSp();
  }

  Future<void> loadSp() async {
    userType = await getSp().getUserType();
    headPortrait.value = await getSp().getUserHeadPortrait();
    if (headPortrait.value == "" && userType != UserType.property) {
      var userInfo = await _meAccountConnect.getUserInfo();
      headPortrait.value = userInfo?.image ?? "";
    }
  }
}
